#include<iostream>
#include<string>
#include<cstdio>
#include<unistd.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>

class  TcpSocket
{
  private:
    int _sockfd;
  public:
    TcpSocket()
      :_sockfd(-1)
    {}
    ~TcpSocket(){}
    bool Socket()
    {
      _sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
      if(_sockfd<0)
      {
        perror("socket error");
        return false;
      }
      return true;
    }

    int fd()
    {
      return _sockfd;
    }
    void set(int fd)
    {
      _sockfd = fd;
    }

    bool Bind(const std::string& ip,uint16_t  port)
    {
      struct sockaddr_in addr;
      addr.sin_family = AF_INET;
      addr.sin_port = htons(port);
      addr.sin_addr.s_addr = inet_addr(ip.c_str());
      socklen_t addrlen = sizeof(struct sockaddr_in);

      int ret = bind(_sockfd,(struct sockaddr*)&addr,addrlen);
      if(ret < 0)
      {
        perror("bind error");
        return false;
      }
      return true;
    }

    bool Listen(int backlog = 10)
    {
      int ret = listen(_sockfd,backlog);
      if(ret < 0)
      {
        perror("listen error");
        return false;
      }
      return true;
    }

    bool Accept(TcpSocket* sock,std::string* cli_ip=NULL,uint16_t* cli_port=NULL)
    {
      struct sockaddr_in peer;
      socklen_t len = sizeof(struct sockaddr_in);
      int newfd = accept(_sockfd,(struct sockaddr*)&peer,&len);
      if(newfd < 0)
      {
        perror("accept error");
        return false;
      }
      sock->_sockfd = newfd;
      if(cli_ip!=NULL)
      {
        *cli_ip = inet_ntoa(peer.sin_addr);
      }
      if(cli_port!=NULL)
      {
        *cli_port = ntohs(peer.sin_port);
      }
      return true;
    }

    bool Recv(std::string* buf)
    {
      char temp[1024] = {0};
      ssize_t ret = recv(_sockfd,temp,1023,0);
      if(ret < 0)
      {
        perror("recv error");
        return false;
      }
      else if(ret == 0)
      {
        printf("connect borken");
      }
      buf->assign(temp,ret);
      return true;
    }

    bool Send(const std::string& buf)
    {
      ssize_t ret = send(_sockfd,buf.c_str(),buf.size(),0);
      if(ret < 0)
      {
        perror("send error");
        return false;
      }
      return true;
    }

    bool Connect(const std::string& ip,int port)
    {
      struct sockaddr_in addr;
      addr.sin_family = AF_INET;
      addr.sin_port = htons(port);
      addr.sin_addr.s_addr = inet_addr(ip.c_str());
      socklen_t len = sizeof(struct sockaddr_in);
      int ret = connect(_sockfd,(struct sockaddr*)&addr,len);
      if(ret < 0)
      {
        perror("connect error");
        return false;
      }
      return true;
    }

    bool Close()
    {
      if(_sockfd!=-1)
      {
        close(_sockfd);
        _sockfd = -1;
      }
      return true;
    }
};
